﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Web;
using Newtonsoft.Json;
using App.Goods.BaseObject;
using App.Helpers;
using App.Common;
using App.BaseObject;

namespace App.Web.admin
{
    /// <summary>
    /// common 的摘要说明
    /// </summary>
    public class common : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "application/json";

            switch (context.Request["action"]) {
                case "getIcons":
                    GetIcons(context);
                    break;
                case "getModels":
                    GetModels(context);
                    break;
                case "codeGeneration":
                    CodeGeneration(context);
                    break;
            }
        }

        /// <summary>
        /// icons
        /// </summary>
        /// <param name="context"></param>
        public void GetIcons(HttpContext context)
        {
            using (var sr = new StreamReader(context.Server.MapPath("~/App_Data/icons.txt")))
            {
                var icons = new List<string>();
                var line = "";
                while ((line = sr.ReadLine()) != null)
                {
                    icons.Add(line.Substring(0, line.IndexOf(" ", StringComparison.Ordinal)));
                }

                var jsonString = JsonConvert.SerializeObject(icons);

                context.Response.Write(jsonString);
            }
        }

        /// <summary>
        /// 获取要生成代码的模型数据
        /// </summary>
        /// <param name="context"></param>
        public void GetModels(HttpContext context)
        {
            using (var sr = new StreamReader(context.Server.MapPath("~/App_Data/models.txt")))
            {
                var models = new List<ModelViewModel>();
                var line = "";
                while ((line = sr.ReadLine()) != null)
                {
                    if (line.StartsWith("#")) continue;
                    var modelText = line.Split(',');
                    models.Add(new ModelViewModel
                    {
                        Id = modelText[0],
                        ModelName = modelText[0],
                        ModelDescription = modelText[1],
                        ModelGroup = modelText[2],
                        UISaveType = modelText[3],
                        ExistField = modelText[4]
                    });
                }

                var jsonString = JsonConvert.SerializeObject(new GridResult { total = models.Count, rows = models });

                context.Response.Write(jsonString);
            }
        }

        /// <summary>
        /// 代码生成
        /// </summary>
        /// <param name="context"></param>
        public void CodeGeneration(HttpContext context)
        {
            var gen = JsonConvert.DeserializeObject<GenerationViewModel>(context.Request["gen"]);
            var projectDirectory = GetSolutionDir();
            var hash = new Dictionary<string, object>();
            var properties = Type.GetType("App."+ gen.model.ModelGroup +"." + gen.model.ModelName + ",App.Core").GetProperties();

            hash.Add("dtoFields", properties);
            hash.Add("properties", properties);
            hash.Add("model", gen.model);

            var nvelocity = NVelocityHelper.GetInstance().GetTemplate(gen.option, "/admin/GenerationTemplates/", hash);

            var outputPath = string.Format(projectDirectory + gen.outputPath, gen.model.ModelGroup, gen.model.ModelName);

            FileOperate.WriteFile(outputPath, nvelocity.ToString());

            var jsonString = JsonConvert.SerializeObject(new OperationResult { success = true, message = "位置：" + outputPath });

            context.Response.Write(jsonString);
        }

        /// <summary>
        /// 获取解决方案路径
        /// </summary>
        /// <returns></returns>
        private string GetSolutionDir()
        {
            var projectDirs = AppDomain.CurrentDomain.BaseDirectory.Split('\\');
            var solutionDir = "";
            var i = 0;
            foreach (var item in projectDirs)
            {
                if (i < projectDirs.Length - 2) solutionDir += item + "\\";
                i++;
            }
            return solutionDir;
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}